package worker

import (
	"context"
	"errors"
	"fmt"
	"time"

	"gorm.io/gorm"
	"zhonghui/console/warehouse/dbx"
	"zhonghui/console/warehouse/dbx/cache_main"
	"zhonghui/console/warehouse/dbx/db_zh_kernel"
	"zhonghui/console/warehouse/helperx"
	"zhonghui/console/warehouse/logx"
	"zhonghui/console/warehouse/servicex"
)

type P struct {
}

func (w *P) Start() {
	w.do()
}

type ModelP struct {
	ID     uint64
	Phone  string
	Name   string
	Idcard string
	Age    int
	Gender int
}

func (w *P) do() {
	defer func() {
		if r := recover(); r != nil {
			logx.Zap().Errorw("定时任务异常", "err", errors.New(fmt.Sprintf("%s", r)))
		}
	}()

	rc := cache_main.Client()
	lock, ch, err := dbx.GetRedisLockWithRefresh(rc, dbx.RedisPrefix("locker-ModelP"), 5*time.Second, time.Second)
	if err != nil {
		return
	}
	defer func() {
		if ch != nil {
			ch <- 1
		}
		_ = lock.Release(context.Background())
	}()

	list := make([]ModelP, 0)
	db_zh_kernel.Client().Table("p").Where("gender = 0").FindInBatches(&list, 1000, func(tx *gorm.DB, batch int) error {
		for _, item := range list {
			if !helperx.IsPhone(item.Phone) {
				db_zh_kernel.Client().Exec("update p set buy = 200 where id = ?", item.ID)
				continue
			}

			card, err := servicex.ParseIdCard(item.Idcard)
			if err != nil {
				db_zh_kernel.Client().Exec("update p set buy = 100 where id = ?", item.ID)
				continue
			}
			gender := 1
			if card.Gender == "f" {
				gender = 2
			}

			db_zh_kernel.Client().Exec("update p set age = ?, gender = ? where id = ?", card.Age, gender, item.ID)
		}

		return nil
	})
}
